<template>
  <el-card class="announcement-card" shadow="hover">
    <div slot="header" class="card-header">
      <div class="header-left">
        <i class="el-icon-bell"></i>
        <span>系统公告</span>
      </div>
      <div class="header-right">
        <router-link to="/announcements" class="more-link">
          查看更多 <i class="el-icon-arrow-right"></i>
        </router-link>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>
    
    <!-- 无数据状态 -->
    <el-empty 
      v-else-if="announcements.length == 0" 
      description="暂无公告信息" 
      :image-size="100">
    </el-empty>
    
    <!-- 公告列表 -->
    <div v-else class="home-announcement-list">
      <div 
        v-for="item in announcements" 
        :key="item.id" 
        class="home-announcement-item"
        @click="viewDetail(item.id)">
        <div class="item-title">
          <el-tag 
            v-if="item.priority === 2" 
            size="mini" 
            type="danger" 
            effect="dark">紧急</el-tag>
          <el-tag 
            v-else-if="item.priority === 1" 
            size="mini"
            type="warning" 
            effect="plain">重要</el-tag>
          <span class="title-text">{{ item.title }}</span>
        </div>
        <div class="item-meta">
          <span><i class="el-icon-document"></i> {{ item.type }}</span>
          <span><i class="el-icon-time"></i> {{ formatDate(item.created_at) }}</span>
        </div>
      </div>
    </div>
  </el-card>
</template>

<script>
import announcementApi from '@/api/announcement';

export default {
  name: 'AnnouncementCard',
  props: {
    // 显示的公告数量
    limit: {
      type: Number,
      default: 5
    }
  },
  data() {
    return {
      // 加载状态
      loading: true,
      
      // 公告列表
      announcements: []
    };
  },
  created() {
    // 获取公告列表
    this.fetchAnnouncements();
  },
  methods: {
    /**
     * 获取公告列表
     */
    fetchAnnouncements() {
      this.loading = true;
      
      // 构造查询参数
      const params = {
        pageNum: 1,
        pageSize: this.limit,
        status: 1 // 只查询已发布的公告
      };
      
      // 调用接口获取数据
      announcementApi.getAnnouncements(params)
        .then(response => {
          if (response && response.data) {
            // 修改这里，使用正确的数据结构路径
            // 后端返回的数据结构是 {code, msg, data: {total, rows}}
            this.announcements = response.data.rows || [];
            console.log('获取到的公告数据:', this.announcements);
            this.normalizeAnnouncements();
          } else {
            this.announcements = [];
            console.error('获取公告列表失败');
          }
        })
        .catch(error => {
          console.error('获取公告列表出错', error);
          this.announcements = [];
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    /**
     * 查看公告详情
     * @param {number} id - 公告ID
     */
    viewDetail(id) {
      // 记录查看次数
      announcementApi.incrementViewCount(id).catch(() => {});
      
      // 跳转到详情页
      this.$router.push(`/announcements/detail/${id}`);
    },
    
    /**
     * 格式化日期
     * @param {string} dateStr - 日期字符串
     * @returns {string} - 格式化后的日期
     */
    formatDate(dateStr) {
      if (!dateStr) return '';
      
      try {
        // 处理多种可能的日期格式
        let date;
        if (typeof dateStr === 'string') {
          // 如果是普通的日期时间字符串格式(不含T)，先标准化为ISO格式
          if (dateStr.indexOf('T') === -1) {
            // 替换空格为T，确保格式正确
            dateStr = dateStr.replace(/\s+/g, 'T');
          }
          // 标准化日期格式
          date = new Date(dateStr);
        } else {
          date = new Date(dateStr);
        }
        
        // 检查日期是否有效
        if (isNaN(date.getTime())) {
          console.warn('无效的日期格式:', dateStr);
          return dateStr; // 返回原始字符串
        }
        
        return date.toLocaleDateString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit'
        });
      } catch (error) {
        console.error('日期格式化错误:', error, dateStr);
        return dateStr; // 出错时返回原始字符串
      }
    },
    
    /**
     * 标准化公告数据
     */
    normalizeAnnouncements() {
      // 确保各个字段名称一致性
      this.announcements = this.announcements.map(item => {
        return {
          id: item.id || 0,
          title: item.title || '无标题',
          type: item.type || '其他',
          priority: item.priority || 0,
          created_at: item.createdAt || item.created_at || new Date().toISOString()
        };
      });
    }
  }
};
</script>

<style scoped>
.announcement-card {
  margin-bottom: 20px;
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

.header-left i {
  margin-right: 8px;
  font-size: 18px;
  color: #409EFF;
}

.more-link {
  font-size: 14px;
  color: #409EFF;
  text-decoration: none;
  display: flex;
  align-items: center;
}

.more-link i {
  margin-left: 4px;
}

.loading-container {
  padding: 10px 0;
}

.home-announcement-list {
  margin-top: 10px;
}

.home-announcement-item {
  padding: 10px 0;
  border-bottom: 1px dashed #EBEEF5;
  cursor: pointer;
  transition: all 0.3s;
}

.home-announcement-item:hover {
  background-color: #F5F7FA;
}

.home-announcement-item:last-child {
  border-bottom: none;
}

.item-title {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
  line-height: 1.4;
}

.title-text {
  font-size: 14px;
  color: #303133;
  margin-left: 5px;
  /* 确保标题不会太长 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.item-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

.item-meta span {
  display: flex;
  align-items: center;
}

.item-meta i {
  margin-right: 4px;
}

@media (max-width: 768px) {
  .item-meta {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .item-meta span {
    margin-bottom: 4px;
  }
}
</style> 